package com.powernode.controller;

import com.powernode.domain.SysMenu;
import com.powernode.domain.SysRole;
import com.powernode.domain.SysUser;
import com.powernode.service.SysMenuService;
import com.powernode.service.SysRoleService;
import com.powernode.service.SysUserService;
import com.powernode.utils.PowerAuthMenuUtil;
import com.powernode.vo.MenusAndAuthors;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单接口管理")
public class SysMenuController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/nav")
    @ApiOperation(value = "获取菜单权限和列表")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public ResponseEntity sysMenuAndAuthors() {
        //需要返回权限列表和菜单列表
        //封装一个对象 里面用来保存这两个list
        Long sysUserId = PowerAuthMenuUtil.getSysUserId();
        //查询所有的列表
        List<SysMenu> menus = sysMenuService.getMenusByUserId(sysUserId);
        //获取所有的权限
        Authentication userAuthors = PowerAuthMenuUtil.getSysUserAuthors();
        Collection<? extends GrantedAuthority> authorities = userAuthors.getAuthorities();
        //转换为List类型
        List<String> authors = authorities.stream().map(auth -> auth.getAuthority()).collect(Collectors.toList());
        MenusAndAuthors menusAndAuthors = new MenusAndAuthors();
        menusAndAuthors.setMenuList(menus);
        menusAndAuthors.setAuthorities(authors);
        return ResponseEntity.ok(menusAndAuthors);
    }

    @GetMapping("/table")
    @ApiOperation(value = "菜单管理")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public ResponseEntity<List<SysMenu>> getRoleList() {
        List<SysMenu> list = sysMenuService.list();
        return ResponseEntity.ok(list);
    }

    @GetMapping("/list")
    @ApiOperation(value = "菜单列表")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public ResponseEntity<List<SysMenu>> getMenuList() {
        List<SysMenu> list = sysMenuService.list();
        return ResponseEntity.ok(list);
    }

    /**
     * 菜单数据新增
     * @param sysMenu
     * @return
     */
    @PostMapping
    @ApiOperation(value = "菜单新增")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public ResponseEntity<Void> addMenu(@RequestBody SysMenu sysMenu) {
        sysMenuService.save(sysMenu);
        return ResponseEntity.ok().build();
    }
}
